﻿using System;
using System.Collections.Generic;
using System.Text;
using System.ServiceModel;
using System.ServiceModel.Channels;

namespace Fcdbas.Core.WCF.TransFile.Channels
{

    ///<summary>
    ///时间:   2011-09-15
    ///描述:   WCF 通道简易缓存
    ///<summary>
    public static class ChannelContainer
    {
        /// <summary>
        /// 通道缓存
        /// </summary>
        public static IDictionary<string, IChannel> _ChannelCaches;

        /// <summary>
        /// 通道工厂缓存
        /// </summary>
        public static IDictionary<string, ChannelFactory> _FactoryCaches;

        /// <summary>
        /// 通过配置节名称获取通道
        /// </summary>
        /// <typeparam name="TChannel">通道类型</typeparam>
        /// <returns>通道</returns>
        public static TChannel GetChannel<TChannel>() where TChannel : class
        {
            string typeName = typeof(TChannel).Name;
            return GetChannel<TChannel>(typeName);
        }

        /// <summary>
        /// 通过配置节名称获取通道
        /// </summary>
        /// <typeparam name="TChannel">通道类型</typeparam>
        /// <param name="configurationName">通道配置名称</param>
        /// <returns>通道</returns>
        public static TChannel GetChannel<TChannel>(string configurationName) where TChannel : class
        {
            if (_ChannelCaches == null)
            {
                _ChannelCaches = new Dictionary<string, IChannel>();
            }

            string typeName = configurationName;

            if (!_ChannelCaches.ContainsKey(typeName))
            {
                CreateNewChannel<TChannel>(typeName);
            }
            else
            {
                IChannel channel = _ChannelCaches[typeName];
                if (channel.State == CommunicationState.Closing 
                    || channel.State == CommunicationState.Closed 
                    || channel.State == CommunicationState.Faulted)
                {
                    _ChannelCaches[typeName] = CreateNewChannel<TChannel>(typeName);
                }
            }

            return _ChannelCaches[typeName] as TChannel;
        }

        /// <summary>
        /// 创建信通道
        /// </summary>
        /// <typeparam name="TChannel">通道类型</typeparam>
        /// <param name="configurationName">通道配置名称</param>
        /// <returns>通道</returns>
        private static IChannel CreateNewChannel<TChannel>(string configurationName) where TChannel : class
        {
            if (_FactoryCaches == null)
            {
                _FactoryCaches = new Dictionary<string, ChannelFactory>();
            }

            CustomChannelFactory<TChannel> factory = new CustomChannelFactory<TChannel>(configurationName);
            TChannel channel = factory.CreateChannel();
            return _ChannelCaches[configurationName] = channel as IChannel;
        }
    }
}
